﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Xms.Abp.Core;

public class ClusterUri : Uri
{
    public ClusterUri(string url) : base(ReplaceUrl(url))
    {
        OriginalString = url;
        var hosts = GetHosts(url);
        Hosts = hosts.Split(',').Select(r =>
        {
            var sp = r.Split(':');
            return new ClusterHost(sp[0], int.Parse(sp[1]));
        }).ToArray();
    }

    //private new string Host { get; }
    //private new int Port { get; }

    public ClusterHost[] Hosts { get; }
    public new string OriginalString { get; }

    private static string ReplaceUrl(string url)
    {
        var sp1 = url.Split("://");
        var sp2 = sp1[1].Split('/', 2);
        var sp3 = sp2[0].Split(',', 2);
        return $"{sp1[0]}://{sp3[0]}/{sp2[1]}";
    }

    public override string ToString()
    {
        return OriginalString;
    }

    public string ToDataBaseConnectionString()
    {
        return $"Server={Host}; Port={Port}; Database={AbsolutePath.TrimStart('/')}; User Id={UserInfo[..UserInfo.IndexOf(':')]}; Password={UserInfo[(UserInfo.IndexOf(':') + 1)..]}; {Query.TrimStart('?').TrimEnd('&').Replace("&", "; ")}{(!Query.IsNullOrWhiteSpace() && Query.Length > 1 ? ";" : "")}";
    }

    public string ToRedisConnectionString()
    {
        return $"{Hosts.JoinAsString(",")},{Query.TrimStart('?').TrimEnd('&').Replace("&", ",")}";
    }

    private static string GetHosts(string url)
    {
        var sp1 = url.Split("://");
        var sp2 = sp1[1].Split('/', 2);
        if (sp2[0].Contains("@"))
        {
            var sp3 = sp2[0].Split('@', 2);
            return sp3[1];
        }
        return sp2[0];
    }

    public class ClusterHost
    {
        public ClusterHost(string host, int port)
        {
            Host = host;
            Port = port;
        }
        public string Host { get; }
        public int Port { get; }
        public override string ToString()
        {
            return Host + ":" + Port;
        }
    }
}

